<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon :closable="false" center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" :space="200" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cascaderProps" @change="handleChange"
                clearable>
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(value,i) in item.attr_vals" :key="i" :label="value" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示图片要上传到的后台API地址 -->
            <el-upload :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove"
              :on-success="handleSuccess" list-type="picture" :headers="headerObj">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览的模态框 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="previewUrl" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
export default {
	data() {
		return {
			activeIndex: '0',
			addForm: {
				goods_name: '',
				goods_price: null,
				goods_weight: null,
				goods_number: null,
				goods_cat: [], // 分类数组
				pics: [],
				attrs:[], // 参数
				goods_introduce:'' // 介绍
			},
			addFormRules: {
				goods_name: [
					{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur',
					},
					{
						min: 3,
						max: 5,
						message: '长度在 3 到 5 个字符',
						trigger: 'blur',
					},
				],
			},
			cateList: [],
			cascaderProps: {
				expandTrigger: 'hover',
				label: 'cat_name',
				value: 'cat_id',
			},
			// 动态参数数据
			manyData: [],
			// 静态属性数据
			onlyData: [],
			// 图片上传路径
			uploadUrl: 'http://www.tangxiaoyang.vip:8888/api/v2/upload',
			dialogVisible: false,
			// 预览图片的地址
			previewUrl: '',
			// 文件上传时的请求头
			headerObj: {
				Authorization: JSON.parse(sessionStorage.getItem('userInfo'))
					.token,
			},
		}
	},
	created() {
		this.getCateList()
	},
	methods: {
		async getCateList() {
			// 获取分类列表数据
			const { data: res } = await this.$http.get('categories')
			if (res.meta.status !== 200) {
				return this.$message.error('获取商品分类失败！')
			}
			this.cateList = res.data
		},
		// 切换tab之前触发
		beforeTabLeave() {
			if (this.addForm.goods_cat.length !== 3) {
				this.$message.error('请先选择分类')
				return false
			}
		},
		handleChange() {
			if (this.addForm.goods_cat.length !== 3) {
				this.addForm.goods_cat = []
			}
		},
		// 点击标签页时触发
		async tabClicked() {
			if (this.activeIndex === '1') {
				// 获取动态参数
				const { data: res } = await this.$http.get(
					`categories/${this.cateId}/attributes`,
					{
						params: { sel: 'many' },
					}
				)
				res.data.forEach((item) => {
					item.attr_vals = item.attr_vals
						? item.attr_vals.split(' ')
						: []
				})
				this.manyData = res.data
				console.log(this.manyData)
			} else if (this.activeIndex === '2') {
				// 获取静态属性
				const { data: res } = await this.$http.get(
					`categories/${this.cateId}/attributes`,
					{
						params: { sel: 'only' },
					}
				)
				this.onlyData = res.data
			}
		},
		handleRemove(file, fileList) {
			// 1.获取将要删除的图片的临时路径
			const filePath = file.response.data.tmp_path
			// 2.从pics数组中，找到这个图片对应的索引值
			const i = this.addForm.pics.findIndex((item) => {
				return item.pic === filePath
			})
			// 3.从pics数组中删除
			this.addForm.pics.splice(i, 1)

			console.log(this.addForm)
		},
		handlePreview(file) {
			this.previewUrl = file.url
			this.dialogVisible = true
		},
		// 图片上传成功时触发
		handleSuccess(response, file, fileList) {
			this.addForm.pics.push({
				pic: response.data.tmp_path,
			})
			console.log(this.addForm)
		},
		async addGoods(){
			/**
			 * 	准备请求前的数据
			 */
			// 处理分类数据
			this.addForm.goods_cat = this.addForm.goods_cat.join(',')

			// 处理动态参数
			this.manyData.forEach(item => {
				this.addForm.attrs.push({
					attr_id:item.attr_id,
					attr_value:item.attr_vals.join(' ')
				})
			})

			// 处理静态参数
			this.onlyData.forEach(item => {
				this.addForm.attrs.push({
					attr_id:item.attr_id,
					attr_value:item.attr_vals
				})
			})

			const {data:res} = await this.$http.post('goods',this.addForm)
			if(res.meta.status !== 201){
				return this.$message.error('添加商品失败')
			}
			this.$message.success('添加商品成功')
			this.$router.push('/goods')
		}
	},
	computed: {
		cateId() {
			return this.addForm.goods_cat.length === 3
				? this.addForm.goods_cat[2]
				: null
		},
	},
}
</script>

<style lang="less" scoped>
.el-steps {
	margin: 15px 0;
}
.previewImg {
	width: 100%;
}
</style>